import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { CoreModule } from '@abp/ng.core';
import { NotificationOrder, NotificationOrderService, NotificationOrderFilter } from './notification-order.service';
import { ToasterService } from '@abp/ng.theme.shared';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-notification-order',
  template: `
    <div class="page-transition">
      <div class="modern-card fade-in">
        <div class="card-header d-flex justify-content-between align-items-center">
          <h4><i class="fas fa-clipboard-list me-2"></i>进货通知明细</h4>
        </div>
        <div class="card-body">
          <!-- 搜索区域 -->
          <div class="search-area">
            <div class="search-title">
              <i class="fas fa-search"></i>
              <span>搜索条件</span>
            </div>
            <form (ngSubmit)="search()" class="modern-form">
              <div class="row">
                <div class="col-md-3">
                  <div class="form-group">
                    <label>通知单号</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.notificationOrderNo" name="notificationOrderNo" placeholder="请输入通知单号">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>客户编码</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.customerCode" name="customerCode" placeholder="请输入客户编码">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>客户名称</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.customerName" name="customerName" placeholder="请输入客户名称">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>商品编码</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.productCode" name="productCode" placeholder="请输入商品编码">
                  </div>
                </div>
              </div>
              <div class="row mt-2">
                <div class="col-md-3">
                  <div class="form-group">
                    <label>商品名称</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.productName" name="productName" placeholder="请输入商品名称">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>客户订单号</label>
                    <input type="text" class="form-control" [(ngModel)]="filter.customerOrderNo" name="customerOrderNo" placeholder="请输入客户订单号">
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="form-group">
                    <label>通知单状态</label>
                    <select class="form-control" [(ngModel)]="filter.notificationStatus" name="notificationStatus">
                      <option [ngValue]="undefined">全部</option>
                      <option value="已完成">已完成</option>
                      <option value="计划中">计划中</option>
                    </select>
                  </div>
                </div>
              </div>
            </form>
          </div>

          <!-- 工具栏 -->
          <div class="toolbar">
            <div class="right-actions">
              <button type="submit" class="modern-btn btn-info" (click)="search()">
                <i class="fas fa-search"></i>
                <span>查询</span>
              </button>
              <button type="button" class="modern-btn btn-secondary" (click)="reset()">
                <i class="fas fa-sync"></i>
                <span>重置</span>
              </button>
            </div>
          </div>
          
          <!-- 数据表格 -->
          <div class="table-responsive mt-3">
            <ngx-datatable
              class="material modern-table"
              [rows]="items"
              [columnMode]="'force'"
              [headerHeight]="50"
              [footerHeight]="50"
              [rowHeight]="'auto'"
              [count]="totalCount"
              [externalPaging]="true"
              [externalSorting]="true"
              [loadingIndicator]="isLoading"
              [limit]="pageSize"
              [offset]="pageNumber"
              (page)="onPage($event)"
              (sort)="onSort($event)"
            >
              <ngx-datatable-column name="通知单号" prop="notificationOrderNo">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-file-alt me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="客户编码" prop="customerCode">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-user me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="客户名称" prop="customerName">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-building me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="通知单状态" prop="notificationStatus">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <span class="status-badge" [ngClass]="{
                    'status-pending': value === '计划中',
                    'status-completed': value === '已完成'
                  }">
                    <i class="fas" [ngClass]="{
                      'fa-clock': value === '计划中',
                      'fa-check-circle': value === '已完成'
                    }"></i>
                    {{ value }}
                  </span>
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="商品编码" prop="productCode">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-barcode me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="商品名称" prop="productName">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-box me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="通知单数量" prop="notificationQty">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-calculator me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="验收数量" prop="receivedQty">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-check-square me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="单位" prop="unit">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-ruler me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="体积(CM3)" prop="volumeCm3">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-cube me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="重量(KG)" prop="weightKg">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-weight me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="客户订单号" prop="customerOrderNo">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-shopping-cart me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="基本单位数量" prop="baseUnitQty">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-calculator me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="基本单位" prop="baseUnit">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="fas fa-ruler me-1"></i>{{ value }}
                </ng-template>
              </ngx-datatable-column>
              <ngx-datatable-column name="生产日期" prop="productionDate">
                <ng-template let-value="value" ngx-datatable-cell-template>
                  <i class="far fa-calendar-alt me-1"></i>{{ value | date: 'yyyy-MM-dd' }}
                </ng-template>
              </ngx-datatable-column>
            </ngx-datatable>
          </div>

          <!-- 加载动画 -->
          <div *ngIf="isLoading" class="text-center mt-3">
            <div class="loading-spinner mx-auto"></div>
          </div>
        </div>
      </div>
    </div>
  `,
  standalone: true,
  imports: [CommonModule, FormsModule, NgxDatatableModule, ThemeSharedModule, CoreModule],
  styleUrls: ['../shared/purchase.styles.scss']
})
export class NotificationOrderComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  items: NotificationOrder[] = [];
  totalCount = 0;
  pageSize = 10;
  pageNumber = 0;
  sorting = '';
  isLoading = false;

  filter: NotificationOrderFilter = {
    maxResultCount: this.pageSize,
    skipCount: 0,
    sorting: '',
    notificationOrderNo: undefined,
    customerCode: undefined,
    customerName: undefined,
    notificationStatus: undefined,
    productCode: undefined,
    productName: undefined,
    customerOrderNo: undefined
  };

  constructor(
    private service: NotificationOrderService,
    private toaster: ToasterService
  ) {}

  ngOnInit(): void {
    this.search();

    // 订阅刷新事件
    this.service.refresh$
      .pipe(takeUntil(this.destroy$))
      .subscribe(() => {
        this.search();
      });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  search(): void {
    this.isLoading = true;
    const params = {
      ...this.filter,
      maxResultCount: this.pageSize,
      skipCount: this.pageNumber * this.pageSize,
      sorting: this.sorting,
    };

    this.service.getListByQuery(params).subscribe({
      next: (result) => {
        if (Array.isArray(result)) {
          this.items = result;
          this.totalCount = result.length;
        } else {
          this.items = result.items;
          this.totalCount = result.totalCount;
        }
        this.isLoading = false;
      },
      error: (error) => {
        console.error('查询失败:', error);
        this.toaster.error('查询失败，请重试');
        this.isLoading = false;
      }
    });
  }

  reset(): void {
    this.pageNumber = 0;
    this.filter = {
      maxResultCount: this.pageSize,
      skipCount: 0,
      sorting: '',
      notificationOrderNo: undefined,
      customerCode: undefined,
      customerName: undefined,
      notificationStatus: undefined,
      productCode: undefined,
      productName: undefined,
      customerOrderNo: undefined
    };
    this.search();
  }

  onPage(event: any): void {
    if (this.pageNumber !== event.offset || this.pageSize !== event.limit) {
      this.pageNumber = event.offset;
      this.pageSize = event.limit;
      this.filter.maxResultCount = this.pageSize;
      this.filter.skipCount = this.pageNumber * this.pageSize;
      this.search();
    }
  }

  onSort(event: any): void {
    const sortField = event.sorts[0];
    this.sorting = sortField ? `${sortField.prop} ${sortField.dir}` : '';
    this.search();
  }
} 